#!/usr/bin/env python3
"""
系统资源检查脚本
检查CPU核心数、内存、GPU等系统资源配置
"""

import os
import platform
import sys


def main():
    """主函数"""
    print("系统资源检查工具")
    print("=" * 50)

    # CPU信息
    print("=== CPU信息 ===")
    print(f"CPU核心数: {os.cpu_count()}")
    print(f"系统架构: {platform.machine()}")
    print(f"操作系统: {platform.system()}")

    # 内存信息
    print("\n=== 内存信息 ===")
    try:
        if platform.system() == "Darwin":  # macOS
            import subprocess

            result = subprocess.run(
                ["sysctl", "-n", "hw.memsize"], capture_output=True, text=True
            )
            if result.returncode == 0:
                memory_bytes = int(result.stdout.strip())
                memory_gb = memory_bytes / (1024**3)
                print(f"总内存: {memory_gb:.1f} GB")
    except Exception as e:
        print(f"无法获取内存信息: {e}")

    # GPU信息
    print("\n=== GPU信息 ===")
    try:
        import torch

        print(f"PyTorch版本: {torch.__version__}")

        if torch.backends.mps.is_available():
            print("✅ MPS (Apple Silicon GPU) 可用")
        else:
            print("❌ MPS 不可用")

        if torch.cuda.is_available():
            print(f"✅ CUDA 可用，设备数量: {torch.cuda.device_count()}")
        else:
            print("❌ CUDA 不可用")

    except ImportError:
        print("PyTorch 未安装，无法检查GPU支持")
    except Exception as e:
        print(f"GPU检查出错: {e}")

    # 项目配置
    print("\n=== 项目配置 ===")
    try:
        # 添加项目根目录到Python路径
        script_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(script_dir)
        sys.path.insert(0, project_root)

        from src.speech_convert.config.funasr_config import CONFIG

        print(f"配置的CPU核心数: {CONFIG.server.DEFAULT_NCPU}")
        print(f"GPU设备: {CONFIG.server.DEFAULT_DEVICE}")
        print(f"启用GPU: {'是' if CONFIG.server.DEFAULT_NGPU else '否'}")
        print(f"服务器端口: {CONFIG.server.DEFAULT_PORT}")

        # 验证配置是否与系统匹配
        if CONFIG.server.DEFAULT_NCPU == os.cpu_count():
            print("✅ CPU核心数配置与系统匹配")
        else:
            print(
                f"⚠️ CPU核心数配置({CONFIG.server.DEFAULT_NCPU})与系统实际核心数({os.cpu_count()})不匹配"
            )

    except ImportError as e:
        print(f"无法导入项目配置: {e}")
    except Exception as e:
        print(f"配置检查出错: {e}")

    print("\n" + "=" * 50)
    print("检查完成！")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"脚本执行出错: {e}")
        import traceback

        traceback.print_exc()
